package com.habdqn.studentmanager.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.PageInfo;
import com.github.xiaofan1519.verify.core.Verify;
import com.github.xiaofan1519.verify.exception.VerifyException;
import com.habdqn.studentmanager.bean.Classes;
import com.habdqn.studentmanager.bean.Dictionary;
import com.habdqn.studentmanager.bean.Product;
import com.habdqn.studentmanager.bean.Student;
import com.habdqn.studentmanager.bean.ajax.RowsResponse;
import com.habdqn.studentmanager.constant.Constant;
import com.habdqn.studentmanager.constant.DictType;
import com.habdqn.studentmanager.constant.ErrorCode;
import com.habdqn.studentmanager.constant.FieldDefine;
import com.habdqn.studentmanager.exception.StudentException;
import com.habdqn.studentmanager.service.ClassesService;
import com.habdqn.studentmanager.service.DictionaryService;
import com.habdqn.studentmanager.service.ProductService;
import com.habdqn.studentmanager.service.StudentService;
import com.habdqn.studentmanager.util.DateUtil;

/**
 * @author Administrator
 * 
 *         2017年5月19日
 * 
 */
@Controller
@RequestMapping("/student")
public class StudentController extends BaseController {

    @Resource
    private StudentService studentService;

    @Resource
    private DictionaryService dictService;

    @Resource
    private ProductService productService;

    @Resource
    private ClassesService classService;

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String toAdd(Model model) {

        List<Dictionary> educations = null;
        List<Product> products = null;
        try {
            educations = dictService.findList(Dictionary.make(DictType.EducationType, null, null));
            products = productService.findProductList(null, null, null).getList();
        }
        catch (StudentException e) {
            setErrMsg(model, "获取字典列表失败");
            return Constant.ERROR_PAGE;
        }

        addAttr(model, "educations", educations);
        addAttr(model, "products", products);
        return "student/add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(Student bean, Model model) {

        try {
            validate(bean);
        }
        catch (VerifyException e) {
            logger.debug("参数校验失败", e);
            setErrMsg(model, "参数非法");
            return Constant.ERROR_PAGE;
        }

        try {
            studentService.insert(bean);
        }
        catch (StudentException e) {
            setErrMsg(model, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        addAttr(model, "msg", "操作成功");
        return "success";
    }

    @RequestMapping("/info")
    public String info(Student bean, Model model) {

        try {
            Verify.verifyNull(bean);
            Verify.verifyNull(bean.getId());
        }
        catch (VerifyException e) {
            logger.debug("参数非法", e);
            setErrMsg(model, "参数非法");
            return Constant.ERROR_PAGE;
        }

        try {
            bean = studentService.find(bean);

            if (null == bean || null == bean.getId()) {
                setErrMsg(model, "没有找到该学员");
                return Constant.ERROR_PAGE;
            }
        }
        catch (StudentException e) {
            setErrMsg(model, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        addAttr(model, "bean", bean);
        return "student/info";
    }

    @RequestMapping("/list")
    public String list(Student student, @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize, Model model) {

        try {
            PageInfo<Classes> classes = classService.findList(null, null, null);
            PageInfo<Product> products = productService.findProductList(null, null, null);

            Product product = null;
            if (null != student && null != student.getClasses() && null != student.getClasses().getProduct()) {
                product = student.getClasses().getProduct();
            }
            PageInfo<Student> pageInfo = studentService.findList(student, product, pageNum, pageSize);
            addAttr(model, "pageInfo", pageInfo);
            addAttr(model, "classes", classes.getList());
            addAttr(model, "products", products.getList());

            // 获取搜索条件
            if (null != student) {
                addAttr(model, "nameValue", student.getName());
                addAttr(model, "studentId", student.getId());
                addAttr(model, "studentStatus", student.getStatus());
                if (null != student.getClasses()) {
                    addAttr(model, "classValue", student.getClasses().getName());

                    if (null != student.getClasses().getProduct()) {
                        addAttr(model, "productValue", student.getClasses().getProduct().getId());
                    }
                }
            }

            return "student/list";
        }
        catch (StudentException e) {
            setErrMsg(model, e.getMessage());
            return Constant.ERROR_PAGE;
        }
    }

    @RequestMapping(value = "/lists", method = RequestMethod.GET)
    @ResponseBody
    public RowsResponse list(Student student, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        RowsResponse rsp = new RowsResponse();
        Product product = null;
        if (null != student && null != student.getClasses() && null != student.getClasses().getProduct()) {
            product = student.getClasses().getProduct();
        }
        try {
            // 获取在读和毕业两个状态学员
            if (null == student) {
                student = new Student();
            }

            student.setExt1("1");
            PageInfo<Student> page = studentService.findList(student, product, pageNum, pageSize);
            rsp.setTotal(page.getTotal());
            rsp.setRows(page.getList());
        }
        catch (StudentException e) {
            rsp.setErr(ErrorCode.System_Error);
            rsp.setMsg(e.getMessage());
            return rsp;
        }

        return rsp;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String toEdit(Student bean, Model model) {

        try {
            Verify.verifyNull(bean);
            Verify.verifyNull(bean.getId());
        }
        catch (VerifyException e) {
            logger.debug("参数非法", e);
            setErrMsg(model, "参数非法");
            return Constant.ERROR_PAGE;
        }

        List<Dictionary> educations = null;
        List<Product> products = null;
        try {
            educations = dictService.findList(Dictionary.make(DictType.EducationType, null, null));
            products = productService.findProductList(null, null, null).getList();

            bean = studentService.find(bean);

            if (null == bean || null == bean.getId()) {
                setErrMsg(model, "没有找到该学员");
                return Constant.ERROR_PAGE;
            }
        }
        catch (StudentException e) {
            setErrMsg(model, "获取字典列表失败");
            return Constant.ERROR_PAGE;
        }

        addAttr(model, "educations", educations);
        addAttr(model, "products", products);
        addAttr(model, "bean", bean);
        return "student/edit";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(Student bean, Model model) {
        
        try {
            validate(bean);
        }
        catch (VerifyException e) {
            logger.debug("参数非法", e);
            setErrMsg(model, "参数非法");
            return Constant.ERROR_PAGE;
        }
        try {
            studentService.update(bean);
        }
        catch (StudentException e) {
            setErrMsg(model, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        addAttr(model, "msg", "操作成功");
        return "success";
    }

    /**
     * 根据筛选条件导出学生数据
     * 
     * @param student
     * @param rsp
     * @param model
     * @return
     */
    @RequestMapping("/export")
    public String export(Student student, HttpServletResponse rsp, Model model) {
        Product product = null;
        if (null != student && null != student.getClasses() && null != student.getClasses().getProduct()) {
            product = student.getClasses().getProduct();
        }

        String fileName = DateUtil.format(DateUtil.now(DateUtil.CHINA_TIMEZONE), DateUtil.FormatStr14) + ".xlsx";
        try {
            OutputStream out = rsp.getOutputStream();
            // 设置强制下载不打开
            rsp.setContentType("application/force-download");
            // 设置文件名
            rsp.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            studentService.export(student, product, out);
        }
        catch (StudentException e) {
            setErrMsg(model, e.getMessage());
            return Constant.ERROR_PAGE;
        }
        catch (IOException e) {
            logger.error("请求异常", e);
            setErrMsg(model, "请求异常");
            return Constant.ERROR_PAGE;
        }

        return null;
    }

    /**
     * 转发至导入页面
     * 
     * @return
     */
    @RequestMapping(value = "/import", method = RequestMethod.GET)
    public String toImport() {

        return "student/import";
    }

    /**
     * 转发至导入页面
     * 
     * @return
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public String importStudent(@RequestParam("file") CommonsMultipartFile file, Model model) {

        try {
            InputStream is = file.getInputStream();
            studentService.importStudent(is);
        }
        catch (StudentException e) {
            setErrMsg(model, e.getMessage());
            return "student/import";
        }
        catch (RuntimeException e) {
            logger.error("系统异常", e);
            setErrMsg(model, "系统异常");
            return "student/import";
        }
        catch (IOException e) {
            logger.error("打开上传文件失败", e);
            setErrMsg(model, "打开上传文件失败");
            return "student/import";
        }

        model.addAttribute("success", "导入成功");
        return "student/import";
    }

    /**
     * 入库参数校验
     * 
     * @param bean
     */
    public static void validate(Student bean) {
        Verify.verifyNull(bean);
        Verify.verifyLen(bean.getId(), FieldDefine.MIN_NAME_LENGTH, 50);
        Verify.verifyLen(bean.getName(), FieldDefine.MIN_NAME_LENGTH, FieldDefine.MAX_NAME_LENGTH);
        Verify.verifyLen(bean.getSex(), 1, 1);
        Verify.verifyLenAllowEmpty(bean.getTextBoxId(), 1, 20);

        Verify.verifyLen(bean.getTel(), 1, 50);
        Verify.verifyLen(bean.getSchool(), 1, 500);
        Verify.verifyLen(bean.getAddress(), 1, 500);

        // Verify.verifyNull(bean.getJoinDate());
        Verify.verifyLen(bean.getIntentionalCity(), 1, 50);
        Verify.verifyLen(bean.getEmail(), 1, 50);
        Verify.verifyEmail(bean.getEmail());
        Verify.verifyLen(bean.getPassCheck(), 1, 50);
        Verify.verifyNull(bean.getEducation());
        Verify.verifyNull(bean.getEducation().getValue());

        Verify.verifyLen(bean.getIdNumber(), 15, 18);
        Verify.verifyLen(bean.getMajor(), 1, 20);

        // 非必填校验
        Verify.verifyLenAllowEmpty(bean.getEmergent(), 1, 50);
        Verify.verifyLenAllowEmpty(bean.getEmergentContact(), 1, 50);
        Verify.verifyLenAllowEmpty(bean.getPreviousJob(), 1, 50);
        Verify.verifyLenAllowEmpty(bean.getJoinWay(), 1, 20);
        Classes clazz = bean.getClasses();
        if (null != clazz) {
            Verify.verifyLenAllowEmpty(clazz.getName(), 1, 50);
        }

        Verify.verifyLenAllowEmpty(bean.getAbnormal(), 0, 500);
        Verify.verifyLenAllowEmpty(bean.getJobIntention(), 0, 500);
        Verify.verifyLenAllowEmpty(bean.getEvaluate(), 0, 500);
        Verify.verifyLenAllowEmpty(bean.getRemarks(), 0, 500);
    }
}
